import request from '@/utils/request'
import type { Permission } from '@/types/rbac'
import type { UserInfo, User } from '@/types/user'
import type { ApiResponse, CaptchaApiResponse, LoginApiResponse, RegisterApiResponse } from './types'

// 获取用户列表
export function getUsersApi(params: {
  page: number
  pageSize: number
  username?: string
  email?: string
  role?: string
  status?: string
}): Promise<ApiResponse<User[]>> {
  return request.get({
    url: '/users',
    params,
  })
}

// 创建用户
export function createUserApi(data: {
  username: string
  email: string
  password: string
  role: string
  department: string
}): Promise<ApiResponse<User>> {
  return request.post({
    url: '/users',
    data,
  })
}

// 更新用户
export function updateUserApi(
  id: number,
  data: {
    username: string
    email: string
    role: string
    department: string
  },
): Promise<ApiResponse<User>> {
  return request.put({
    url: `/users/${id}`,
    data,
  })
}

// 删除用户
export function deleteUserApi(id: number): Promise<ApiResponse<null>> {
  return request.delete({
    url: `/users/${id}`,
  })
}

// 切换用户状态
export function toggleUserStatusApi(
  id: number,
  status: 'active' | 'inactive',
): Promise<
  ApiResponse<{
    id: number
    status: 'active' | 'inactive'
  }>
> {
  return request.patch({
    url: `/users/${id}/status`,
    data: { status },
  })
}

// 登录（对接后端 /auth/login，支持用户名或邮箱+验证码）
export function loginApi(data: {
  usernameOrEmail: string
  password: string
  captcha?: string
  captchaId?: string
}): Promise<ApiResponse<LoginApiResponse>> {
  return request.post({
    url: '/auth/login',
    data: {
      usernameOrEmail: data.usernameOrEmail,
      password: data.password,
      captcha: data.captcha,
      captchaId: data.captchaId,
    },
  })
}

// 获取图形验证码
export function getCaptchaApi(): Promise<CaptchaApiResponse> {
  return request.get({
    url: '/auth/captcha',
  })
}

// 注册（对接后端 /auth/register）
export function registerApi(data: {
  username: string
  email: string
  password: string
  captcha: string
  captchaId: string
}): Promise<ApiResponse<RegisterApiResponse>> {
  return request.post({
    url: '/auth/register',
    data: {
      username: data.username,
      email: data.email,
      password: data.password,
      captcha: data.captcha,
      captchaId: data.captchaId,
    },
  })
}

// 获取用户信息
export function getUserInfoApi(): Promise<UserInfo> {
  return request.get({
    url: '/auth/userinfo',
  })
}

// 获取用户权限树形结构
export function getUserPermissionsApi(userId: number): Promise<ApiResponse<Permission[]>> {
  return request.get({
    url: `/rbac/users/${userId}/permissions`,
  })
}

// 刷新token
export function refreshTokenApi(refreshToken: string): Promise<ApiResponse<{ access_token: string }>> {
  return request.post({
    url: '/auth/refresh',
    data: {
      refresh_token: refreshToken,
    },
  })
}
